package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RedissonClient;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {


    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedissonClient redissonClient ;
    @Resource
    private IVoucherOrderService voucherOrderService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //创建阻塞队列
    private BlockingQueue<VoucherOrder> orderQueue = new ArrayBlockingQueue(1024*1024);
    //创建线程池
    private static final ExecutorService executors = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init(){
        executors.submit(new OrderHandler());
    }

    public class OrderHandler implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    //获取订单信息
                    VoucherOrder voucherOrder = orderQueue.take();
                    //创建订单
                    createVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                }
            }
        }
    }




    // Lua脚本
    private static final DefaultRedisScript<Long> SEC_KILL_SCRIPT;
    static {
        SEC_KILL_SCRIPT = new DefaultRedisScript<>();
        SEC_KILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SEC_KILL_SCRIPT.setResultType(Long.class);
    }

    @Override
    public Result SeckillVoucher(Long voucherId) {
        Long userid = UserHolder.getUser().getId();
        //执行lua脚本
        Long flag = stringRedisTemplate.execute(SEC_KILL_SCRIPT, Collections.emptyList(),  voucherId.toString(),
                userid.toString());

        //判断库存是否充足
        if(flag==1){return Result.fail("库存不足");}
        //判断优惠券是否已经购买过
        if(flag==2){return Result.fail("用户已经购买过");}
        //创建订单id
        long orderId = redisIdWorker.createId("order");

        // todo flag=0 将订单信息添加到阻塞队列中
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userid);
        voucherOrder.setVoucherId(voucherId);
        orderQueue.add(voucherOrder);
        //返回订单id
        return Result.ok(orderId);

    }


    @Transactional(rollbackFor = Exception.class)
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long voucherId = voucherOrder.getVoucherId();
        // 5.判断用户是否已经购买过 每个用户限购一张
        Integer count = query().eq("user_id", voucherOrder.getUserId())
                .eq("voucher_id", voucherId)
                .count();
        if (count > 0) {
            log.error("用户已经购买过");
        }

        // 扣减库存

        //5.1是否扣减库存成功
        boolean flag = seckillVoucherService.update()
                .setSql("stock=stock-1")
                .eq("voucher_id", voucherId)
                //.eq("stock", Voucher.getStock())
                .gt("stock", 0)
                .update();
        if (!flag) {
           log.error("库存不足");
        }
        voucherOrderService.save(voucherOrder);
    }

    /*@Override
    public Result SeckillVoucher(Long voucherId) {

        // 1.查询优惠券
        SeckillVoucher Voucher = seckillVoucherService.getById(voucherId);
        // 2.判断优惠券是否存在
        if(Voucher == null || ObjectUtil.isEmpty(Voucher)){
            return Result.fail("优惠券不存在");
        }
        // 3.判断优惠券是否开启秒杀
        if (Voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("优惠券尚未开始");
        }
        // 4.判断秒杀是否结束
        if (Voucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("优惠券已结束");
        }

        // 5.判断库存是否充足
        if (Voucher.getStock() < 1) {
            return Result.fail("库存不足");
        }
        Long userid = UserHolder.getUser().getId();
        RLock lock = redissonClient.getLock("lock:order:" + userid);
        // 6.获取锁
        boolean isLock = lock.tryLock();
        //SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:" + userid , stringRedisTemplate);
        //boolean isLock = simpleRedisLock.tryLock(10L);
        if(!isLock){
            //未获取锁
            return Result.fail("请勿重复下单");
        }
        try {
            //通过自身代理对象调用方法，避免事务失效
            return voucherOrderService.createVoucherOrder(voucherId);
        } finally {
            // 只有当前线程持有锁时，才释放锁
            if(lock.isHeldByCurrentThread()){lock.unlock();}


        }

    }*/


    /*@Transactional(rollbackFor = Exception.class)
    public Result createVoucherOrder(Long voucherId) {
        // 5.判断用户是否已经购买过 每个用户限购一张
        Integer count = query().eq("user_id", UserHolder.getUser()
                        .getId())
                .eq("voucher_id", voucherId)
                .count();
        if (count > 0) {
            return Result.fail("用户已经购买过");
        }

        // 扣减库存

        //5.1是否扣减库存成功
        boolean flag = seckillVoucherService.update()
                .setSql("stock=stock-1")
                .eq("voucher_id", voucherId)
                //.eq("stock", Voucher.getStock())
                .gt("stock", 0)
                .update();
        if (!flag) {
            return Result.fail("库存扣减失败");
        }
        //6.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //补全订单信息

        //补全订单id，用户id，代金券id
        UserDTO user = UserHolder.getUser();
        long orderId = redisIdWorker.createId("order");
        voucherOrder.setUserId(user.getId());
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setId(orderId);
        voucherOrderService.save(voucherOrder);
        return Result.ok(orderId);
    }*/
}
